package com.bawei.movie

import android.util.Log
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.base.RoutePath
import com.bawei.common.mvi.BaseMviFragment
import com.bawei.movie.adapter.MovieViewPagerAdapter
import com.bawei.movie.databinding.FragmentMovieBinding
import com.bawei.movie.entity.MovieTypeEntity
import com.bawei.movie.intent.MovieViewIntent
import com.bawei.movie.state.MovieUiState
import com.bawei.movie.vm.MovieViewModel
import com.google.android.material.tabs.TabLayoutMediator
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.interfaces.OnSelectListener
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

@AndroidEntryPoint
@Route(path = RoutePath.PATH_FRAGMENT_MOVIE)
class MovieFragment : BaseMviFragment<FragmentMovieBinding>() {

    private val mViewModel: MovieViewModel by activityViewModels()

    private var searchHints = mutableListOf("热门影视", "头条视频", "动作电影")

    private lateinit var mViewPageAdapter: MovieViewPagerAdapter
    private var fragments = mutableListOf<MovieListFragment>()
    private var oneTypeList = mutableListOf<MovieTypeEntity>()
    private var twoTypeList = mutableListOf<MovieTypeEntity>()

    private var leverOneTypeId = 1

    private lateinit var mXPopupBuilder: XPopup.Builder


    override fun getLayoutId(): Int = R.layout.fragment_movie

    override fun initViews() {
        mDataBinding.tbvSearch.setDatas(searchHints)
        //创建Popup
        mXPopupBuilder = XPopup.Builder(requireContext()).atView(mDataBinding.cltFilter)

        //筛选的点击事件
        mDataBinding.tvFilter.setOnClickListener {
            showMovieTypeFilter()
        }
        mViewPageAdapter = MovieViewPagerAdapter(fragments, this@MovieFragment.childFragmentManager, lifecycle)
        mDataBinding.vpVideo.offscreenPageLimit = 4
        mDataBinding.vpVideo.adapter = mViewPageAdapter

        //关联TabLayout和ViewPager2
        TabLayoutMediator(mDataBinding.tabTypeLayout, mDataBinding.vpVideo){tab, position ->
            tab.text = twoTypeList[position].typename
        }.attach()
    }

    private fun showMovieTypeFilter(){
        if(oneTypeList.isNotEmpty()){
            var menuNameList = mutableListOf<String>()
            oneTypeList.forEach {
                menuNameList.add(it.typename)
            }
            mXPopupBuilder.asAttachList(menuNameList.toTypedArray(), null) { position, _ ->
                leverOneTypeId = oneTypeList[position].id
                //发送意图新的二级分类
                loadNewTwoTypeById()
            }.show()
        }
    }

    private fun loadNewTwoTypeById(){
        lifecycleScope.launch {
            mViewModel.channel.send(MovieViewIntent.LoadLeverTwoType(leverOneTypeId))
        }
    }

    override suspend fun sendViewIntent() {
        mViewModel.channel.send(MovieViewIntent.LoadLeverOneType)
        mViewModel.channel.send(MovieViewIntent.LoadLeverTwoType(leverOneTypeId))
    }

    override suspend fun collectUiState() {
        mViewModel.uiState.collect{
            when(it){
                is MovieUiState.LoadLeverOneTypeSuccess -> initLeverOneTypePopupWindow(it.list)
                is MovieUiState.LoadLeverTwoTypeSuccess -> initLeverTwoTypeLayout(it.list)
                is MovieUiState.LoadLeverTwoTypeFail -> loadTwoTypeFail()
                is MovieUiState.LoadLeverOneTypeFail -> {}
                else -> {}
            }
        }
    }

    private fun loadTwoTypeFail(){
        twoTypeList.clear()
        fragments.clear()
        mDataBinding.tabTypeLayout.removeAllTabs()

        //添加推荐Tab实体
        twoTypeList.add(MovieTypeEntity("", 0, -1, 0,"tuijian", "推荐"))
        fragments.add(ARouter.getInstance().build(RoutePath.PATH_FRAGMENT_MOVIE_LIST).withInt("tabId", -1).navigation() as MovieListFragment)

        //Tab标签设置
        twoTypeList.forEach {
            mDataBinding.tabTypeLayout.addTab(mDataBinding.tabTypeLayout.newTab().setText(it.typename))
        }

        //重置适配器，防止缓存导致页面展示与分类不匹配问题（非常重要）
        mDataBinding.vpVideo.adapter = mViewPageAdapter
        //更新UI数据
        mViewPageAdapter.notifyDataSetChanged()
    }

    private fun initLeverOneTypePopupWindow(list: List<MovieTypeEntity>) {
        if(oneTypeList.size > 0){
            oneTypeList.clear()
        }
        oneTypeList.addAll(list)
    }

    private fun initLeverTwoTypeLayout(list: List<MovieTypeEntity>) {
        if(list.isNotEmpty()){
            twoTypeList.clear()
            fragments.clear()
            mDataBinding.tabTypeLayout.removeAllTabs()

            //添加推荐Tab实体和页面Fragment
            twoTypeList.add(MovieTypeEntity("", 0, -1, 0, "tuijian", "推荐"))
            fragments.add(ARouter.getInstance().build(RoutePath.PATH_FRAGMENT_MOVIE_LIST).withInt("tabId", -1).navigation() as MovieListFragment)

            //添加其他分类Tab实体和页面Fragment
            list.forEach {
                twoTypeList.add(it)
                fragments.add(ARouter.getInstance().build(RoutePath.PATH_FRAGMENT_MOVIE_LIST).withInt("tabId", it.id).navigation() as MovieListFragment)
            }

            //创建Tab组件，并添加到分类布局容器中
            twoTypeList.forEach {
                mDataBinding.tabTypeLayout.addTab(mDataBinding.tabTypeLayout.newTab().setText(it.typename))
            }

            //重置适配器，防止分类重复
            mDataBinding.vpVideo.adapter = mViewPageAdapter
            mViewPageAdapter.notifyDataSetChanged()

        }
    }







}